const dashboard = document.querySelector('.dashboard');
let checkboxList;
let lastChecked;

const updateList = () => {
    checkboxList = document.querySelectorAll('.dash-item input');
    checkboxList.forEach(item => {
        item.addEventListener('click', checkHandler);
        item.parentNode.querySelector('button').addEventListener('click', deleteItem);
    });
};

function deleteItem(e) {
    this.parentNode.remove();
    updateList();
}

const addNewItemHandler = () => {
    const newItem = document.createElement('div');
    newItem.classList.add('dash-item');

    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    const pEl = document.createElement('p');
    pEl.setAttribute('contenteditable', '');
    const button = document.createElement('button');
    button.innerHTML = '&times;';

    newItem.append(checkbox, pEl, button);
    dashboard.appendChild(newItem);

    updateList();
}

function checkHandler(e) {
    if (e.shiftKey && this.checked) {
        const newArray = Array.from(checkboxList);
        const startIndex = newArray.indexOf(this);
        const endIndex = newArray.indexOf(lastChecked);

        for (let i = startIndex; i !== endIndex; (startIndex > endIndex ? i-- : i++)) {
            newArray[i].checked = true;
        }
    }

    lastChecked = this;
}

updateList();
document.querySelector('.btn-add').addEventListener('click', addNewItemHandler);